﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace UDITool
{
    public class UDI
    {
        #region 系统复制 粘贴相关
        [DllImport("user32.dll", SetLastError = true)]
        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
        static void PressKey(Keys key, bool up)
        {
            const int KEYEVENTF_EXTENDEDKEY = 0x1;
            const int KEYEVENTF_KEYUP = 0x2;
            if (up)
            {

                keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, (UIntPtr)0);

            }
            else
            {

                keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr)0);

            }
        }
        #endregion

        /// <summary>
        /// 递归解析UDI码
        /// </summary>
        /// <param name="udi"></param>
        /// <param name="code"></param>
        public static void AnalysisUDI(UDICode udi, string code)
        {
            if (string.IsNullOrEmpty(code)) return; // 没有可以解析的 直接return
            string nextCode;
            if (code.StartsWith("01"))
            {
                if (code.Length <= 16)
                {
                    udi.Di = code.Substring(2);
                    return;
                }
                else
                {
                    udi.Di = code.Substring(2, 14);
                    nextCode = code.Substring(2 + udi.Di.Length);
                    AnalysisUDI(udi, nextCode);
                }
            }

            if (code.StartsWith("10"))
            {
                udi.BatchNumber = code.Substring(2);
                return;
            }

            if (code.StartsWith("11"))
            {
                udi.ProductionDate = code.Substring(2, 6);
                nextCode = code.Substring(8);
                AnalysisUDI(udi, nextCode);
            }

            if (code.StartsWith("17"))
            {
                udi.ExpirationDate = code.Substring(2, 6);
                nextCode = code.Substring(8);
                AnalysisUDI(udi, nextCode);
            }

            if (code.StartsWith("21"))
            {
                udi.SerialNumber = code.Substring(2);
            }
        }

        /// <summary>
        /// 键盘输出
        /// </summary>
        /// <param name="sendMsg"></param>
        public static void KeyOutPut(string sendMsg)
        {
            // 将字符串复制到剪贴板
            Clipboard.SetText(sendMsg);

            PressKey(Keys.ControlKey, false);
            PressKey(Keys.V, false);
            PressKey(Keys.V, true);
            PressKey(Keys.ControlKey, true);
            PressKey(Keys.Enter, false);
            PressKey(Keys.Enter, true);
        }
    }
}

